package com.tiantianyuegou.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tiantianyuegou.R;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ProductModel;
import com.tiantianyuegou.model.StoreModel;
import com.tiantianyuegou.util.ToastUtilsCenter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 确认订单的adapter
 * Created by ivany on 2016/1/12.
 */
public class ConfirmOrderAdapter extends BaseAdapter {

    private Context mContext;
    private List<StoreModel> mData;

    private Map<Integer, View> priceMap = new HashMap<>();
    private Map<Integer, View> countMap = new HashMap<>();

    public interface ISelectCouponListener {
        void selectCoupon(int positoin);//选择优惠券

        void reCalcuate(List<StoreModel> mData);//重新计算价格

    }

    private ISelectCouponListener mListener;

    public void setSelectCouponListener(ISelectCouponListener listener) {
        mListener = listener;
    }

    public ConfirmOrderAdapter(Context context) {
        mContext = context;
        mData = new ArrayList<>();
    }

    public ConfirmOrderAdapter(Context context, List<StoreModel> data) {
        mContext = context;
        mData = data;
    }

    public void setData(List<StoreModel> data) {
        mData = data;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder = new ViewHolder();
        //if (convertView == null) {
        convertView = LayoutInflater.from(mContext).inflate(R.layout.item_confirm_oreder, null);
//            holder = new ViewHolder();
        holder.mTxt_store_name = (TextView) convertView.findViewById(R.id.item_confirm_store_name);
//        holder.mRl_usecount = (RelativeLayout) convertView.findViewById(R.id.confirm_relate_useCount);
        holder.mRl_coupon = (RelativeLayout) convertView.findViewById(R.id.confirm_relate_coupon);
//        holder.mTxt_express = (TextView) convertView.findViewById(R.id.confirm_express);
        holder.mLinear_product = (LinearLayout) convertView.findViewById(R.id.item_confirm_product);
        holder.mEt_useCount = (EditText) convertView.findViewById(R.id.item_confirm_usecount_et);
        holder.mTxt_countPrice = (TextView) convertView.findViewById(R.id.item_confirm_usecount_price);
        holder.mRl_usecount_input = (RelativeLayout) convertView.findViewById(R.id.confirm_relate_inputCount);
//        holder.mImg_usecount = (ImageView) convertView.findViewById(R.id.confirm_usecount_img);
        holder.mTxt_coupon_value = (TextView) convertView.findViewById(R.id.confirm_coupon_value);
//        holder.mTxt_useCount = (TextView) convertView.findViewById(R.id.confirm_usecount);
        convertView.setTag(holder);
//        } else {
//            holder = (ViewHolder) convertView.getTag();
//        }
//        priceMap.put(position, holder.mTxt_countPrice);
//        countMap.put(position, holder.mEt_useCount);
        final StoreModel store = mData.get(position);
        holder.mTxt_store_name.setText(store.getStoreName());
        holder.mTxt_express.setText("快递:" + store.getExpress() + "元");
        holder.mTxt_useCount.setText("(共" + store.getTotalGuan() + "个,可用" + store.getCanUseGuan() + "个)");
        if (store.getCoupon() != null && !"0".equals(store.getCoupon())) {
            holder.mTxt_coupon_value.setText("￥" + store.getCoupon());
        }
        //在动态添加之前先清除之前的view
        holder.mLinear_product.removeAllViews();
        //动态添加产品界面
        for (int i = 0; i < store.getProductModels().size(); i++) {
            final ProductModel model = store.getProductModels().get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_confirm_product, holder.mLinear_product, false);
            ImageView productPic = ((ImageView) view.findViewById(R.id.item_confirm_product_img));
            //设置商品图片
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(mContext));
            ImageLoader.getInstance().displayImage(model.getUrl(), productPic);

            ((TextView) view.findViewById(R.id.item_confirm_product_name)).setText(model.getName());
            ((TextView) view.findViewById(R.id.item_confirm_product_spec)).setText(model.getSpec());
            ((TextView) view.findViewById(R.id.item_confirm_product_price)).setText(model.getPrice());
            final TextView mTxt_num = (TextView) view.findViewById(R.id.item_confirm_product_num);
            mTxt_num.setText(model.getNumber());
            TextView mTxt_reduce = (TextView) view.findViewById(R.id.item_confirm_product_reduce);
            //产品界面上的减按钮
            mTxt_reduce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    store.setCoupon("0");
                    store.setCouponId(-1);
                    holder.mTxt_coupon_value.setText("");
                    int num = Integer.valueOf(mTxt_num.getText().toString());
                    if (1 == num) {
                    } else {
                        num = num - 1;
                        mTxt_num.setText(num + "");
                        model.setNumber(num + "");
                        mListener.reCalcuate(mData);
                    }
                }
            });
            //产品界面上的加按钮
            final TextView mTxt_add = (TextView) view.findViewById(R.id.item_confirm_product_add);
            mTxt_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.mTxt_coupon_value.setText("");
                    store.setCoupon("0");
                    store.setCouponId(-1);
                    int num = Integer.valueOf(mTxt_num.getText().toString());
                    if (num >=model.getStore()) {
                    } else {
                        num = num + 1;
                        mTxt_num.setText(num + "");
                        model.setNumber(num + "");
                        mListener.reCalcuate(mData);
                    }
                }
            });
            //添加
            holder.mLinear_product.addView(view);
        }
        //根据是否被选择来决定使用贯的输入是否显示
        if (mData.get(position).isUseGuan()) {
            holder.mRl_usecount_input.setVisibility(View.VISIBLE);
            holder.mImg_usecount.setImageResource(R.mipmap.select_icon);
        } else {
            holder.mEt_useCount.setText("");
            holder.mRl_usecount_input.setVisibility(View.GONE);
            holder.mImg_usecount.setImageResource(R.mipmap.unselect_icon);
        }
        //贯抵现点击事件
        holder.mRl_usecount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mData.get(position).setUseGuan(!mData.get(position).isUseGuan());
                if (!mData.get(position).isUseGuan()) {
                    mData.get(position).setUseGuanVlaue("0");
                    holder.mEt_useCount.setText("");
                    holder.mRl_usecount_input.setVisibility(View.GONE);
                    holder.mImg_usecount.setImageResource(R.mipmap.unselect_icon);
                    mListener.reCalcuate(mData);
                } else {
                    holder.mRl_usecount_input.setVisibility(View.VISIBLE);
                    holder.mImg_usecount.setImageResource(R.mipmap.select_icon);
                }
            }
        });
        //是否使用贯
        if (store.isUseGuan()) {
            String value = store.getUseGuanVlaue();
            String unitPrice = store.getUnitPrice();
            if (value != null && !"0".equals(value)) {
                holder.mEt_useCount.setText(value);
                holder.mTxt_countPrice.setText(new DecimalFormat("0.00").format(Double.valueOf(value) * (Double.valueOf(unitPrice))) + "元");
            }
        } else {
            holder.mEt_useCount.setText("");
            holder.mTxt_countPrice.setText("0.00元");
        }
        //输入框的输入监听事件
        holder.mEt_useCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //改变抵现金额
                String value = s.toString();
                Log.e("TAG", "value:" + value + ":total guan :" + SPHelper.getTmGuanCount());
                int canUse = Integer.parseInt(store.getCanUseGuan());
                int total = Integer.parseInt(store.getTotalGuan());
//                int totalGuan = Integer.parseInt(SPHelper.getTmGuanCount());
                if (value != null && !"".equals(value)) {
                    if (Integer.valueOf(value) > canUse) {
                     ToastUtilsCenter.makeText(mContext, "可用贯个数为" + canUse, false).show();
                        holder.mEt_useCount.setText("");
                    } else if (Integer.valueOf(value) > total) {
                        ToastUtilsCenter.makeText(mContext, "您的总贯数为" + total, false).show();
                        holder.mEt_useCount.setText("");
                    } else {
                        String unitPrice = store.getUnitPrice();
                        holder.mTxt_countPrice.setText(new DecimalFormat("0.00").format(Double.valueOf(value) * (Double.valueOf(unitPrice))) + "元");
                        mData.get(position).setUseGuanVlaue(value);

                        //重新计算价格
                        mListener.reCalcuate(mData);
                    }
                } else {
                    holder.mTxt_countPrice.setText("0.00元");
                    mData.get(position).setUseGuanVlaue("0");

                    //重新计算价格
                    mListener.reCalcuate(mData);
                }
            }
        });

        //使用优惠券
        holder.mRl_coupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.selectCoupon(position);
            }
        });
        return convertView;
    }


    class ViewHolder {
        TextView mTxt_store_name;
        TextView mTxt_express;
        TextView mTxt_useCount;
        RelativeLayout mRl_usecount;
        ImageView mImg_usecount;
        RelativeLayout mRl_coupon;
        LinearLayout mLinear_product;
        EditText mEt_useCount;
        TextView mTxt_countPrice;
        RelativeLayout mRl_usecount_input;
        TextView mTxt_coupon_value;
    }
}
